#!/usr/bin/env python
# coding:utf-8
from __future__ import absolute_import
from celery import Celery, Task
from django.conf import settings
import os
from main.functions.load_plugins import get_task_plugin
from main.models import TaskResults


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")

app = Celery('tasks')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


class BackupTask(Task):
    name = 'backup_task'

    def run(self, *args, **kwargs):
        if len(args) != 1:
            print('plugin name is not giving.')
        else:
            plugin_name = args[0]
            plugin = get_task_plugin(plugin_name)
            plugin(*args, **kwargs).execute()

    def on_success(self, retval, task_id, args, kwargs):
        result = TaskResults.objects.create(task_id = task_id,
                                            task_name = self.name,
                                            plugin_name=args[0],
                                            kwargs = kwargs,
                                            retval=retval if retval else '',
                                            status = 'successed')
        result.save()

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        print("exc type:{}, einfo type:{}".format(type(exc), type(einfo)))


class OtherTask(Task):
    name = 'other_task'

    def run(self, *args, **kwargs):
        # 根据arg找到任务插件的实例，将kwargs传入该实例，然后就执行吧，很爽的

        # get_backup_plugin()

        return args, kwargs


class RestoreTask(Task):
    name = 'restore_task'

    def run(self, *args, **kwargs):
        return args, kwargs
